﻿using HalconDotNet;
using Halcon二次开发.Controller.CamerForm交互;
using Halcon二次开发.Controller.主界面交互;
using Halcon二次开发.Controller.卡尺;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.输入框;
using log4net;
using log4net.Config;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Halcon二次开发.Controller.数据加载与保存;
using System.Reflection;
using Halcon二次开发.View.多模板匹配;
using Halcon二次开发.View.Socket通信;
using MvCameraControl;
using Halcon二次开发.View.精准测量模块;
using Halcon二次开发.View.应用_加载框;
using Halcon二次开发.View.工位监控画面;
using Halcon二次开发.View.登录界面;
using Halcon二次开发.View.账号信息界面;
using Halcon二次开发.View.配置界面;
using Halcon二次开发.Model.配置信息;
using System.Xml.Linq;
using Halcon二次开发.View.相机;
using System.Net.NetworkInformation;
using 可视化工具.View.创建工程;
using 可视化工具.Model.工程文件保存属性类;
using System.Collections.Generic;
using System.Threading;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;

[assembly: XmlConfigurator(ConfigFile = "Data\\日志配置文件\\log4net.config", Watch = true)]
namespace Halcon二次开发
{
    public partial class Form1 : Form
    {
        //控制监视磁盘线程的变量
        public static bool delImagePaper = true;
        //控制进行工程文件的标志
        public bool getHomeFormPaper = true;
        /// <summary>
        /// 工程文件路径
        /// </summary>
        public string filePath = $@"Data\工程文件\";//创建文件时会修改这个工程的默认路径
        /// <summary>
        /// 程序默认路径
        /// </summary>
        public string approvePath = $@"Data\工程文件\";//这个路径是不会修改的
        /// <summary>
        /// 当前工程文件的名称
        /// </summary>
        public string projectName = null;
        //日志文件对象
        public static readonly ILog log = LogManager.GetLogger(typeof(Form1));
        //程序加载界面
        
        Form load;
        public Form1(LoadForm loadForm)
        {
            this.load = loadForm;
            InitializeComponent();
            //单例窗体
            FormDb.Db.Add("Form1", this);
            HOperatorSet.SetSystem("clip_region", "false");
        }
        /// <summary>
        /// 双击添加流程节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int index = tabControl2.SelectedIndex;
            if (index == -1)
            {
                textBox1.AppendText("请先添加工程文件!\r\n");
                return;
            }
            HwindowFlowNodeUrseControl s = tabControl2.TabPages[index].Tag as HwindowFlowNodeUrseControl;
            //这里要判断一下
            foreach (var item in StaicResouce.formCollections)
            {
                if (item.name == tabControl2.TabPages[index].Text)
                {
                    item.Btn_Double_Click(s, treeView1);
                }
            }
        }
        /// <summary>
        /// 新建任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //获取菜单栏的上一个父级    openNameCreate:当前创建文件的工程名称
            string openNameCreate =((ToolStripMenuItem)sender).OwnerItem.Text;
            //如果filePath路径没变那么就是不能去创建工程文件了
            if (!ShowFilePathNULL())
            {
                textBox1.AppendText("新建任务失败!\r\n");
                return;
            }
            string[] silpName = openNameCreate.Split(new char[] { '工', '程', '文', '件' });
            if (projectName != silpName[0])
            {
                textBox1.AppendText("请选择该工程再进行增加任务!\r\n");
                return;
            }
            //路径选择窗口
            NameForm nameForm = new NameForm();
            nameForm.fathName = silpName[0];//将当前工程名字给到文件路径选择
            nameForm.ShowDialog(this);
            if (nameForm.name == "")
            {
                return;
            }else if (nameForm.name.Contains("任务文件"))
            {
                MessageBox.Show("文件名不能包含\"任务文件\"");
            }

            //将这个新增的菜单添加到对应的菜单中.DropDownItems.Add(nameForm.name + "任务文件");
            ToolStripMenuItem t1 = (ToolStripMenuItem)((ToolStripMenuItem)sender).OwnerItem;
            ToolStripMenuItem addsToolStream = new ToolStripMenuItem(nameForm.name + "任务文件");
            t1.DropDownItems.Add(addsToolStream);
            ToolStripMenuItem delToolStream = new ToolStripMenuItem("-删除任务-");
            addsToolStream.DropDownItems.Add(delToolStream);//增加一个删除任务
            delToolStream.Click += MenuItemMove_Click;//点击删除任务事件
            //添加界面 
            HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl = new HwindowFlowNodeUrseControl();
            //对这个动作进行新增
            Form1Controller form1Controller = new Form1Controller();
            form1Controller.name = nameForm.name;
            //将大工程名字给到FormController
            form1Controller.SetFilePath(projectName);
            form1Controller.hwindowFlowNode = hwindowFlowNodeUrseControl;  //绑定上去,代替静态变量
            StaicResouce.formCollections.Add(form1Controller);
            //这俩步非常重要,动作绑定窗体
            hwindowFlowNodeUrseControl.name = nameForm.name;
            hwindowFlowNodeUrseControl.projectName=projectName;//所属的操作工程名
            hwindowFlowNodeUrseControl.form1Controller = form1Controller;
            MonitoringForm.GetMonitoringForm().AddFramesTime(hwindowFlowNodeUrseControl);
            hwindowFlowNodeUrseControl.framesTimeForm = new FramesTimeForm(hwindowFlowNodeUrseControl, MonitoringForm.GetMonitoringForm());
            Utiy.AddPage(hwindowFlowNodeUrseControl, tabControl2, nameForm.name);
            //对这个新增的页面进行记录
            StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
        }
        /// <summary>
        /// Tab页更改时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = tabControl2.SelectedIndex;
            if (index == -1) return;
            HwindowFlowNodeUrseControl s = tabControl2.TabPages[index].Tag as HwindowFlowNodeUrseControl;


            //TODO: StaicResouce.HwindowFlowNodeUrse = s;
        }
        //Text消息框更改,写入日志文件
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            log.Error(textBox1.Text);
        }
        /// <summary>
        /// 预加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //加载工程文件的默认路径@"Data\默认工程文件保存\上一次工程名称.json"
            string paths = @"Data\默认工程文件保存\上一次工程名称.json";
            ProjectDomain domain = HelpJsons.ReadObject<ProjectDomain>(paths);
            if (domain != null)
            {
                //对当前工程文件名进行赋值
                filePath = domain.path;
                projectName = domain.name;
            }
            string state = approvePath+ projectName;//根目录 //例子 ：\Data\工程文件    
            //加载工程文件到菜单栏上
            AddPreloadMenuItemStrip();
            if (Directory.Exists(state))
            {
                string[] stateS = Directory.GetDirectories(state);// 查询所有工程文件
                foreach (string item in stateS)//循环创建所有任务文件
                {
                    LoadStation(item);
                }
                if (stateS.Length > 0)
                {
                    tabControl2.SelectedIndex = 0;
                }
                splitContainer1.SplitterDistance = splitContainer1.Height / 3 * 2;
            }
            //加载配置信息

            //首先要判断存在配置文件
            if (!Directory.Exists(@"Data\配置文件"))
            {
                Directory.CreateDirectory(@"Data\配置文件");
            }
            if (!File.Exists(@"Data\配置文件\AppConfig.config"))
            {
                File.Create(@"Data\配置文件\AppConfig.config").Close();
            }
            string[] configstr = File.ReadAllLines(@"Data\配置文件\AppConfig.config");
            if (configstr.Length < 1) return;
            PathConfig.GetSingle().DiskValue = configstr[0];
        }
        /// <summary>
        /// 加载工程文件
        /// </summary>
        /// <param name="destDir"></param>
        private void LoadStation(string destDir,string paper="")
        {
            try
            {
                //将任务名提取出来
                string[] stateName = destDir.Split(new char[] { '任', '务', '文', '件', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                string name = stateName[stateName.Length - 1];

                int paperOpen = -1;
                foreach (string item in StaicResouce.FilesName.Keys)
                {
                    if (item.Equals(projectName))
                    {
                        paperOpen = 1;
                    }
                }
                if (paperOpen==-1)
                {
                    StaicResouce.FilesName.Add(projectName, name);
                }
                StaicResouce.homeContolrName.Add(name);
                // projectName:工程名称    nameForm.name：任务名称
                //对这个动作进行新增
                Form1Controller form1Controller = new Form1Controller();
                form1Controller.name = name;
                //将大工程名字给到FormController
                form1Controller.SetFilePath(projectName);
                StaicResouce.formCollections.Add(form1Controller);
                //添加界面
                HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl = new HwindowFlowNodeUrseControl();
                //这俩步非常重要,动作绑定窗体
                hwindowFlowNodeUrseControl.name = name;
                hwindowFlowNodeUrseControl.projectName = projectName;
                hwindowFlowNodeUrseControl.form1Controller = form1Controller;
                //实时监控图像
                MonitoringForm.GetMonitoringForm().AddFramesTime(hwindowFlowNodeUrseControl);
                //MonitoringForm.GetMonitoringForm().GetHSmartWindow(name);
                hwindowFlowNodeUrseControl.framesTimeForm = new FramesTimeForm(hwindowFlowNodeUrseControl,MonitoringForm.GetMonitoringForm());
                //MonitoringForm.GetMonitoringForm().GetHSmartWindow(name).Show();
                //TODO: 这条需要赋值一下,因为第一次Page页选择事件不会被触发
                //StaicResouce.HwindowFlowNodeUrse = hwindowFlowNodeUrseControl;
                Utiy.AddPage(hwindowFlowNodeUrseControl, tabControl2, name);

                //对这个新增的页面进行记录
                if (paper!="开启")//当不是切换，不进行添加
                {
                    StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
                }
                bool addPaper = false;
                foreach (HwindowFlowNodeUrseControl item in StaicResouce.HomeForms)
                {
                    //判断这个工程是否存在
                    if (item.projectName==projectName)
                    {
                        addPaper = true;
                    }
                }
                //如果这个工程不存在就是打开的工程
                if (!addPaper)
                {
                    StaicResouce.HomeForms.Add(hwindowFlowNodeUrseControl);
                }
                //遍历流程文件 创建项目流程
                string flowFile = destDir + "\\流程\\流程.txt";
                if (File.Exists(flowFile))
                {
                    string[] tools = File.ReadAllLines(flowFile);
                    for (int i = 0; i < tools.Length; i++)
                    {

                        string[] results = tools[i].Split(new char[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        object classInstance = CreateObjectByName(results[0], hwindowFlowNodeUrseControl);
                        //这里就是2个PMA模板匹配所需的构造方法
                        if (classInstance is H_PMA_S_AlignToolForm)
                        {
                            (classInstance as H_PMA_S_AlignToolForm).SetPathNodes(approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim());
                        }
                        if ((classInstance is Form))
                        {
                            //获取到每个类中的SetJsonPaths方法
                            MethodInfo methodInfo = classInstance.GetType().GetMethod("SetJsonPaths");
                            if (methodInfo != null)
                            {
                                object[] objs = new object[2] { approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim() };
                                methodInfo.Invoke(classInstance, objs);
                            }
                            form1Controller.AddHeadNode((classInstance as Form), results[2].Trim(), hwindowFlowNodeUrseControl, int.Parse(results[3]));
                            foreach (TreeNode targetNode in hwindowFlowNodeUrseControl.treeView1.Nodes)
                            {
                                if (targetNode.Name == results[2].Trim())
                                {
                                    //更改子节点的连接状态 
                                    AddChildLink(ref i, tools, targetNode);
                                }
                            }
                        }
                        if (classInstance is CaliperModuleForm)
                        {
                            if (classInstance == null) continue;
                            foreach (TabPage pag in (classInstance as CaliperModuleForm).ParentPanl.TabPages)
                            {
                                if (pag == null || pag.Tag == null) continue;

                                MethodInfo methodInfo = pag.Tag.GetType().GetMethod("SetJsonPaths");
                                if (methodInfo != null)
                                {
                                    object[] objs = new object[2] { approvePath + projectName + "\\" + hwindowFlowNodeUrseControl.name + "任务文件", results[2].Trim() };
                                    methodInfo.Invoke(pag.Tag, objs);
                                }
                            }
                        }
                    }
                }

                //AddMenu(name);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        /// <summary>
        /// 删除工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void 删除工程toolStripMenuItem_Click(object sender, EventArgs e)
        {
            //拿到工程节点
            ToolStripMenuItem toolMenuDown = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
            //拿到路径中的工程文件名
            string projectNames = toolMenuDown.Text.Split('工','程','文','件')[0];
            
            if (projectName== projectNames)//必须是正在操作的工程才可以删除这个工程文件
            {
                bool delPaper = false;
                List<HwindowFlowNodeUrseControl> Indextlist = new List<HwindowFlowNodeUrseControl>();//存储临时下标
                Indextlist.Clear();
                for (int i = 0; i < StaicResouce.HomeForms.Count; i++)
                {
                    HwindowFlowNodeUrseControl hd = StaicResouce.HomeForms[i] as HwindowFlowNodeUrseControl;
                    if (hd.projectName== projectNames)
                    {
                        Indextlist.Add(hd);
                        delPaper =true;
                        //if (StaicResouce.formCollections[i].name == hd.name)
                        //{
                        //    StaicResouce.formCollections.RemoveAt(i);
                        //    break;
                        //}
                    }
                }
                foreach (HwindowFlowNodeUrseControl item in Indextlist)
                {
                    //将对应相机的工位资源释放
                    if (item.camerFormController != null && projectName == item.projectName)
                    {
                        try
                        {
                            if (item.camerFormController.device != null)
                            {
                                int check = item.camerFormController.device.Close();
                                item.camerFormController.device.Dispose();
                                SDKSystem.Finalize();//释放资源
                            }

                        }
                        catch (Exception ex)
                        {
                            // 记录错误信息
                            Console.WriteLine($"设备关闭失败，错误码: {ex.Message}");
                        }
                    }
                    //通过对象去删除
                    StaicResouce.HomeForms.Remove(item);
                }
                if (delPaper)
                {
                    //删除TabPage
                    this.tabControl2.TabPages.Clear();
                    //删除工程节点   获取到根节点
                    ToolStripMenuItem toolMenuUp = ((ToolStripMenuItem)toolMenuDown).OwnerItem as ToolStripMenuItem;
                    toolMenuUp.DropDownItems.Remove(toolMenuDown);
                }
                //删除工程文件夹
                if (Directory.Exists(approvePath + projectName))//工程文件路径
                {
                    Directory.Delete(approvePath + projectName, true);//删除工程文件
                }
            }
            else
            {
                MessageBox.Show("删除工程时，请切换至所对应的工程下，再进行删除工程","消息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 多方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemCopy_Click(object sender, EventArgs e)
        {
            if (true || filePath == @"Data\工程文件\")
            {
                MessageBox.Show("维护中");
                return;
            }

            NameCopyForm nameForm = new NameCopyForm();
            nameForm.ShowDialog(this);
            if (nameForm.name.Trim() == "")
            {
                return;
            }
            //当前节点对象
            ToolStripMenuItem current = sender as ToolStripMenuItem;
            //父节点对象
            ToolStripMenuItem parent = current.Tag as ToolStripMenuItem;
            
            //寻找工程文件
            string[] str = parent.Text.Split(new char[] { '任', '务', '文', '件' }, StringSplitOptions.RemoveEmptyEntries); foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                if (hd.name == str[0].Trim())
                {
                   CloseSave(hd); 
                }
            }
            //源目录
            string sourceDir = filePath + parent.Text;
            //目标目录
            string destDir = filePath  + nameForm.name + "任务文件";
            CopyDirectoryRecursively(sourceDir, destDir);
            LoadStation(destDir);
        }
      
        private void CopyDirectoryRecursively(string sourceDir, string destDir)
        {
            try
            {
                // 检查源目录是否存在
                if (!Directory.Exists(sourceDir))
                {
                    throw new DirectoryNotFoundException("源目录不存在。");
                }
                // 如果目标目录不存在，则创建它
                if (!Directory.Exists(destDir))
                {
                    Directory.CreateDirectory(destDir);
                    if (destDir.Contains("OKNG图片"))
                    {
                        return;
                    }
                }
                // 获取源目录中的所有文件和子目录
                foreach (string file in Directory.GetFiles(sourceDir))
                {
                    // 构造目标文件的路径
                    string destFile = Path.Combine(destDir, Path.GetFileName(file));
                    // 复制文件
                    File.Copy(file, destFile, overwrite: true);
                }

                // 递归复制所有子目录
                foreach (string subDir in Directory.GetDirectories(sourceDir))
                {
                    // 构造目标子目录的路径
                    string destSubDir = Path.Combine(destDir, Path.GetFileName(subDir));
                    // 递归调用 CopyDirectoryRecursively 方法
                    CopyDirectoryRecursively(subDir, destSubDir);
                }
            }
            catch
            {
                MessageBox.Show("多方案失败");
            }
        }
        /// <summary>
        /// 删除任务文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemMove_Click(object sender, EventArgs e)
        {
            RemoveParent(sender, "delete");
        }
        /// <summary> 
        /// 删除父菜单和流程图和tabpag
        /// </summary>
        /// <param name="sender"></param>
        private void RemoveParent(object sender, string mode)
        {
            //任务节点
            ToolStripMenuItem toolMenuDown = ((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
            //工程节点
            ToolStripMenuItem toolMenuUp = ((ToolStripMenuItem)toolMenuDown).OwnerItem as ToolStripMenuItem;
            string projectName = toolMenuUp.Text.Split(new char[] { '工', '程', '文', '件' })[0];
            //删除工程文件  toolMenuDown.Text = aa1   
            string[] str = toolMenuDown.Text.Split(new char[] { '任', '务', '文', '件' }, StringSplitOptions.RemoveEmptyEntries);
            HwindowFlowNodeUrseControl u = null;
            for (int i=0;i<StaicResouce.HomeForms.Count;i++)
            {
                HwindowFlowNodeUrseControl hd = StaicResouce.HomeForms[i] as HwindowFlowNodeUrseControl;
                if (hd.name== str[0].Trim())
                {
                    u = hd;
                    hd.runPaper = false;
                    hd.timer2.Enabled = false;
                    hd.timer3.Enabled = false;
                    hd.timer4.Enabled = false;
                    hd.timer5.Enabled = false;
                    //将对应相机的工位资源释放
                    if (hd.camerFormController != null)
                    {
                        hd.camerFormController.CloseCamer();
                    }
                }
                if (StaicResouce.formCollections[i].name==str[0].Trim())
                {
                    StaicResouce.formCollections.RemoveAt(i);
                    break;
                }
            }
            if (u != null)
            {
                u.runPaper = false;
                u.timer2.Enabled = false;
                u.timer3.Enabled = false;
                u.timer4.Enabled = false;
                u.timer5.Enabled = false;
                u.framesTimeForm.Close();
                StaicResouce.HomeForms.Remove(u);
            }
            //删除tabpag
            Utiy.RemovePage(tabControl2, str[0].Trim());
            //彻底删除工程文件
            if (mode == "delete")
            {
                try
                {
                    Directory.Delete(approvePath + projectName + "\\" + toolMenuDown.Text, true);
                    //删除记录工程文件名的集合
                    StaicResouce.FilesName.Remove(str[0].Trim());
                }
                catch { }
            }
            //根点对象
            ToolStripMenuItem head = toolMenuDown.OwnerItem as ToolStripMenuItem;
            //删除父菜单
            try { if(head!=null) head.DropDownItems.Remove(toolMenuDown); } catch(Exception ex){ }  
        }

        /// <summary>
        /// 递归读取子节点的连线状态
        /// </summary> 
        public void AddChildLink(ref int i, string[] tools, TreeNode node)
        {
            if (!(i < tools.Length - 1) || !tools[i + 1].Contains("<—")) return;
            string[] strs = tools[i + 1].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (TreeNode item in node.Nodes)
            {
                if (item.Name == strs[0])
                {
                    item.Text = strs[1];
                    item.ForeColor = Color.Green;
                    break;
                }
            }
            i++;
            AddChildLink(ref i, tools, node);
        }
        private static object CreateObjectByName(string className, HwindowFlowNodeUrseControl hwindowFlowNode)
        {
            // 通过类名获取类型信息
            Type type = Type.GetType(className);
            if (type == null)
            {
                return null; // 类型不存在
            }

            // 使用Activator.CreateInstance创建类的实例
            return Activator.CreateInstance(type, hwindowFlowNode);
        }
        /// <summary>
        /// 自动保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //将工程文件路径进行保存，存储程序关闭之前的工程名称
            string paths = @"Data\默认工程文件保存\上一次工程名称.json";
            if (!Directory.Exists(@"Data\默认工程文件保存"))
            {
                Directory.CreateDirectory(@"Data\默认工程文件保存");
            }
            HelpJsons.Write<ProjectDomain>(new ProjectDomain(paths, projectName), paths);
           
            //将磁盘线程关闭
            delImagePaper = false;
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                CloseSave(hd);
            }
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
            }
            //存储每个界面的数据
            // * 保存界面数据 注释
            SDKSystem.Finalize();

            //关闭窗体
            load.Close();
        }
        private void CloseSave(HwindowFlowNodeUrseControl hd)
        {

            hd.FormClosing();
            string state = approvePath+ hd.projectName + "\\" + hd.name + "任务文件\\";//例子 ：\Data\工程文件\123工程文件    state
            string flowPath = state + "流程\\";              //例子：\Data\工程文件\123工程文件\流程   flowPath
            string flowFilePath = flowPath + "流程.txt";          //例子：\Data\工程文件\123工程文件\流程\流程.txt   flowFilePath
            if (!Directory.Exists(flowPath))//创建流程文件夹 
            {
                Directory.CreateDirectory(flowPath);
            }
            using (File.Create(flowFilePath)) { }//重新创建工程文件
                                                 //创建或者覆盖界面数据文件夹
            string flowsPaths = state + "界面数据";
            if (!Directory.Exists(flowsPaths))
            {
                //不存在就创建文件夹
                Directory.CreateDirectory(flowsPaths);
            }
            else
            {
                //存在就删除在创建文件夹
                Directory.Delete(flowsPaths, true);
                Directory.CreateDirectory(flowsPaths);
            }

            TreeNodeCollection headNodes = hd.treeView1.Nodes;
            bool delFilePaper = true;
            foreach (TreeNode headNode in headNodes)//新键所有工具根点文件夹
            {
                //在这里将我们的相机工具进行文件的处理
                if (headNode.Name.Equals("相机工具0"))
                {
                    delFilePaper = false;
                }
                string hPath = flowsPaths + "\\" + headNode.Name;//例子：\Data\工程文件\123工程文件\模板匹配0   hPath
                if (!Directory.Exists(hPath))
                {
                    Directory.CreateDirectory(hPath);
                }
                using (StreamWriter writer = new StreamWriter(flowFilePath, append: true))
                {
                    string xxx = headNode.Text;
                    writer.WriteLine(headNode.Tag.ToString() + ":" + headNode.ImageIndex);// 窗体对象+根节点名+根节点显示的图片
                   
                }
            }
            //处理我们的相机工具中的文件了
            if (delFilePaper)
            {
                //如果有这个工具就可以去删除我们的相机文件了
                if (Directory.Exists(state + "相机图片数据"))
                {
                    //有这个文件夹就可以进行覆盖这个文件夹了
                    Directory.Delete(state + "相机图片数据", true);
                    Directory.CreateDirectory(state + "相机图片数据");
                }
            }
        }
        private void socket通信ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SocketForm.GetSocketForm().Show();
        }
        //日志框属性值更改时发生
        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            //log.Error(textBox1.Text);
        }
        //工位实时监控画面
        private void 工位实时监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MonitoringForm.GetMonitoringForm().Show();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //窗体自动获得焦点
            EnterUrseForm.GetSingle(this).BringToFront();
            EnterUrseForm.GetSingle(this).Focus();
            EnterUrseForm.GetSingle(this).ShowDialog();
        }
        public void 超级用户()
        {
            新建ToolStripMenuItem.Enabled = true;
            工程管理ToolStripMenuItem.Enabled = true;
            //通信ToolStripMenuItem.Enabled = true;
            修改密码ToolStripMenuItem.Enabled = true;
            treeView1.Enabled = true;
            uiSplitContainer1.SplitterDistance = 254;
        }
        public void 管理员()
        {
            新建ToolStripMenuItem.Enabled = true;
            工程管理ToolStripMenuItem.Enabled = true;
            //通信ToolStripMenuItem.Enabled = true;
            修改密码ToolStripMenuItem.Enabled = false;
            treeView1.Enabled = true;
            uiSplitContainer1.SplitterDistance = 254;
        }
        public void 操作者()
        {
            新建ToolStripMenuItem.Enabled = false;
            工程管理ToolStripMenuItem.Enabled = false;
            //通信ToolStripMenuItem.Enabled = false;
            treeView1.Enabled = false;
            uiSplitContainer1.SplitterDistance = 0;
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UrseIDForm.GetSingle().Show();

            //窗体自动获得焦点
            UrseIDForm.GetSingle().BringToFront();
            UrseIDForm.GetSingle().Focus();
            UrseIDForm.GetSingle().Show();
        }

        /// <summary>
        /// 配置界面打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm.GetSingle().Show();
            //窗体自动获得焦点
            ConfigForm.GetSingle().BringToFront();
            ConfigForm.GetSingle().Focus();
            ConfigForm.GetSingle().Show();
        }
        /// <summary>
        /// 打开任务文件按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></params
        private void 打开任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog ofd = new FolderBrowserDialog())
            {
                ofd.SelectedPath = Application.StartupPath + $"\\Data\\工程文件\\{projectName}\\";
                // 显示对话框并检查结果
                DialogResult result = ofd.ShowDialog();
                if (result == DialogResult.OK)
                {
                    ToolStripMenuItem toolMenu=((ToolStripMenuItem)sender).OwnerItem as ToolStripMenuItem;
                    //string[] silpName = openNameCreate.Split(new char[] { '工', '程', '文', '件' });
                    // 用户点击了“确定”按钮，获取选中的文件夹路径
                    string selectedFolderPath = ofd.SelectedPath;
                    string[] stateNames = selectedFolderPath.Split(new char[] { '任', '务', '文', '件', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    //获取到任务文件中的名字
                    if (stateNames.Length>=10)//选择正确的文件打开
                    {
                        string stateName = stateNames[stateNames.Length - 1];
                        LoadStation(selectedFolderPath);
                        ToolStripMenuItem addMenuItemMove = new ToolStripMenuItem(stateName+"任务文件");

                        toolMenu.DropDownItems.Add(addMenuItemMove);
                    }else
                    {
                        MessageBox.Show("请选择正确的任务文件，选择正确的文件，进行打开", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    
                }
            }
        }
        /// <summary>
        /// 新建工程文件，大工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //新建大工程文件
            CreateForms nameForm = new CreateForms();
            nameForm.ShowDialog(this);
            if (nameForm.name == "")
            {
                return;
            }else if (nameForm.name.Contains("工程文件"))
            {
                MessageBox.Show("文件名不能包含\"工程文件\"");
            }
            //将当前tabContorl置为null
            tabControl2.TabPages.Clear();
            //创建大工程文件夹
            string paths = approvePath + nameForm.name;
            //有没有工程文件夹
            if (!Directory.Exists(paths))
            {
                Directory.CreateDirectory(paths);
                AddMenuItemStrip(nameForm.name,paths);
            }
        }
        /// <summary>
        /// 预加载工程菜单栏的数据
        /// </summary>
        /// <param name="paths">预加载的路径</param>
        private void AddPreloadMenuItemStrip()
        {
            string[] paths = Directory.GetDirectories(approvePath);
            foreach (string item in paths)
            {
                string directoryName = Path.GetFileName(item);
                AddMenuItemStrip(directoryName,item);
            }
        }
        /// <summary>
        ///  添加工程文件，以及任务文件,这里只是添加菜单栏的
        /// </summary>
        /// <param name="name">工程名</param>
        /// <param name="paths">工程路径</param>
        public void AddMenuItemStrip(string name,string pathss)
        { 
            //将路径的默认路径进行修改
            filePath = pathss;
            //将工程名称给到工程名称变量
            //projectName = name;
            //将工程名增加到集合当中
            StaicResouce.projectList.Add(name);
            //工程文件的路径
            string paths = approvePath +name;
            //将这个工程给到菜单栏的加载当中
            ToolStripMenuItem menuItem1 = new ToolStripMenuItem(name + "工程文件");
            menuItem1.Name = name + "工程文件";
            //新建任务
            ToolStripMenuItem addMenuItemMove = new ToolStripMenuItem("-新建任务-");
            menuItem1.DropDownItems.Add(addMenuItemMove);
            addMenuItemMove.Tag = menuItem1;
            addMenuItemMove.Click += 新建任务ToolStripMenuItem_Click;
            //打开任务
            ToolStripMenuItem openMenuItemMove = new ToolStripMenuItem("-打开任务-");
            menuItem1.DropDownItems.Add(openMenuItemMove);
            openMenuItemMove.Tag = menuItem1;
            openMenuItemMove.Click += 打开任务ToolStripMenuItem_Click;
            //切换工程
            ToolStripMenuItem verifyMenuItems = new ToolStripMenuItem("-切换该工程-");
            menuItem1.DropDownItems.Add(verifyMenuItems);
            verifyMenuItems.Tag = menuItem1;
            verifyMenuItems.Click += 切换工程ToolStripMenuItem_Click;
            //读取当前工程文件下的任务文件
            string[] directories = Directory.GetDirectories(paths);
            foreach (string dir in directories)
            {
                string directoryName = Path.GetFileName(dir);
                string[] strs= directoryName.Split(new char[] { '任','务','文','件'});
                ToolStripMenuItem addToolStream = new ToolStripMenuItem(strs[0] + "任务文件");
                //任务菜单的删除任务
                ToolStripMenuItem delToolStream = new ToolStripMenuItem("-删除任务-");
                addToolStream.DropDownItems.Add(delToolStream);//增加一个删除任务
                delToolStream.Tag = addToolStream;//绑定父菜单
                addToolStream.Tag = menuItem1;//绑定父菜单
                delToolStream.Click += MenuItemMove_Click;//点击删除任务事件
                menuItem1.DropDownItems.Add(addToolStream);//增加到根节点中
            }
            //删除工程
            ToolStripMenuItem delsMenuItemMove = new ToolStripMenuItem("-删除工程-");
            menuItem1.DropDownItems.Add(delsMenuItemMove);
            delsMenuItemMove.Tag = menuItem1;
            delsMenuItemMove.Click += 删除工程toolStripMenuItem_Click;
            //将节点添加到父节点中
            工程管理ToolStripMenuItem.DropDownItems.Add(menuItem1);
            menuItem1.Tag = 工程管理ToolStripMenuItem;
        }

        /// <summary>
        /// 切换工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void 切换工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                string hdName = hd.name;
                CloseSave(hd);
                //将对应相机的工位资源释放
                if (hd.camerFormController != null&&projectName==hd.projectName)
                {
                    try
                    {
                        if (hd.camerFormController.device!=null)
                        {
                            int check = hd.camerFormController.device.Close();
                            hd.camerFormController.device.Dispose();
                            SDKSystem.Finalize();//释放资源
                        }

                    }
                    catch (Exception ex)
                    {
                        // 记录错误信息
                        Console.WriteLine($"设备关闭失败，错误码: {ex.Message}");
                    }
                }
            }
            //"工程号:"+HwindowFlowNodeUrseControl.name + HwindowFlowNodeUrseControl.name + "工位画面监视"
            foreach (FramesTimeForm child in MonitoringForm.GetMonitoringForm().MdiChildren)
            {
                child.Close();
            }
            foreach (HwindowFlowNodeUrseControl hd in StaicResouce.HomeForms)
            {
                new StorageDataController(approvePath + hd.projectName + "\\").Storage(hd);
            }
            //将TabContol控件清空
            this.tabControl2.TabPages.Clear();
            string openNameCreate = ((ToolStripMenuItem)sender).OwnerItem.Text;
            string[] silpName = openNameCreate.Split(new char[] { '工', '程', '文', '件' });
            projectName = silpName[0];//当前操作的工程
            string[] openStringName = Directory.GetDirectories(approvePath + silpName[0]);
            if (openStringName.Length>0)
            {
                StaicResouce.homeContolrName.Clear();//将这个存储当前使用的任务清空
            }
            foreach (string item in openStringName)
            {
                LoadStation(item,"开启");
            }
            
        }

        private bool ShowFilePathNULL()
        {
            if (getHomeFormPaper==false)
            {
                return false;
            }
            //如果filePath路径没变那么就是不能去创建工程文件了
            if (filePath == @"Data\工程文件\")
            {
                MessageBox.Show("请创建工程文件", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                getHomeFormPaper = false;
                return false;
            }
            return true;
        }
        /// <summary>
        /// 打开工程文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 打开工程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog ofd = new FolderBrowserDialog())
            {
                ofd.SelectedPath = Application.StartupPath + $"\\Data\\工程文件\\";
                // 显示对话框并检查结果
                DialogResult result = ofd.ShowDialog();
                if (result == DialogResult.OK)
                {
                    // 用户点击了“确定”按钮，获取选中的文件夹路径
                    string selectedFolderPath = ofd.SelectedPath;
                    //确定它是否为工程文件
                    string[] pathsString=Directory.GetDirectories(selectedFolderPath);
                    //标志位
                    bool projectPaper = false;
                    foreach (string pathus in pathsString)
                    {
                        if (Path.GetFileName(pathus).Contains("任务文件"))//是工程文件
                        {
                            projectPaper = true;
                            break;
                        }
                    }
                    //判断这个工程文件在文件夹是否存在多的同名的工程
                    if (projectPaper)
                    {
                        string[] stateNames = selectedFolderPath.Split(new char[] { '工', '程', '文', '件', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                        string filesName= stateNames[stateNames.Length - 1];
                        string pattern = @"-?\d+";
                        // 使用Regex.Matches提取所有匹配的数字
                        MatchCollection matches = Regex.Matches(filesName.Trim(), pattern);
                        bool matchPaper = false;
                        int matchCount = -1;
                        foreach (Match match in matches)
                        {
                            //将字符转换为数字
                            string matchs = match.Value;
                            if (int.TryParse(matchs,out matchCount))
                            {
                                matchPaper= true;
                                break;
                            }
                        }
                        if (matchPaper&&matchCount!=-1)//有数字的情况自增+1
                        {
                            string[] pathsNames = stateNames[stateNames.Length - 1].Split(new char[] {'多','方','案'});
                            string modifiedString = stateNames[stateNames.Length - 1].Replace(pathsNames[pathsNames.Length-1], matchCount + 1+"");
                            //创建一个工程文件夹  selectedFolderPath:原路径    目标路径:approvePath+ (matchCount + 1)
                            CopyDirectory(selectedFolderPath, approvePath+ modifiedString);
                            //菜单栏的增加
                            AddMenuItemStrip(modifiedString, approvePath + modifiedString);
                            //将数据同步到集合当中

                        }
                        else//没有数字就是1
                        {
                            //创建一个工程文件夹
                            CopyDirectory(selectedFolderPath, approvePath + stateNames[stateNames.Length - 1]+"多方案"+ 1);
                            //菜单栏的增加
                            AddMenuItemStrip(stateNames[stateNames.Length - 1] + "多方案" + 1, approvePath + stateNames[stateNames.Length - 1] + "多方案" + 1);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 递归复制子文件
        /// </summary>
        /// <param name="sourceDir">源文件夹路径</param>
        /// <param name="targetDir">目标文件夹路径</param>
        public void CopyDirectory(string sourceDir, string targetDir)
        {
            // 如果目标文件夹不存在，则创建它
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            // 复制源文件夹中的所有文件到目标文件夹
            foreach (string file in Directory.GetFiles(sourceDir))
            {
                // 获取文件名并构建目标文件路径
                string fileName = Path.GetFileName(file);
                string destFile = Path.Combine(targetDir, fileName);

                // 复制文件
                File.Copy(file, destFile, overwrite: true);  // overwrite为true时会覆盖目标文件
            }

            // 递归复制所有子文件夹
            foreach (string subDir in Directory.GetDirectories(sourceDir))
            {
                // 获取子文件夹的名称并构建目标子文件夹路径
                string subDirName = Path.GetFileName(subDir);
                string destSubDir = Path.Combine(targetDir, subDirName);

                // 递归调用复制子文件夹
                CopyDirectory(subDir, destSubDir);
            }
        }
    }
}
